//
//  ComprehensiveDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/8/21.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

import Charts


class ProfitFormatter: IAxisValueFormatter {
    
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        
        switch Int(value) / 10 {
        case 1:
            return "项目毛利"
        case 2:
            return "项目成本"
        default:
            return "项目收入"
        }
    }
    
}

class ComprehensiveDetailViewController: DemoBaseViewController {

    var companys: Array<JSON> = []
    
    var selectedCompany = ""
    
    @IBOutlet weak var chartView: HorizontalBarChartView!
    
    @IBOutlet weak var companyField: UITextField!
    
    @IBAction func showTheCompany(_ sender: UIButton) {
        
        self.load(with: "GetOrg")
        
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.options = [.toggleValues,
                        .toggleIcons,
                        .toggleHighlight,
                        .animateX,
                        .animateY,
                        .animateXY,
                        .saveToGallery,
                        .togglePinchZoom,
                        .toggleAutoScaleMinMax,
                        .toggleData,
                        .toggleBarBorders]
        
        self.setup(barLineChartView: chartView)
        
        chartView.drawBarShadowEnabled = false
//        chartView.drawValueAboveBarEnabled = true
        
        chartView.maxVisibleCount = 60
        
        let xAxis = chartView.xAxis
        xAxis.labelPosition = .bottom
        xAxis.labelFont = .systemFont(ofSize: 10)
        xAxis.drawAxisLineEnabled = true
        xAxis.granularity = 10
        
        let leftAxis = chartView.leftAxis
        leftAxis.enabled = false
        leftAxis.labelFont = .systemFont(ofSize: 10)
        leftAxis.drawAxisLineEnabled = true
        leftAxis.drawGridLinesEnabled = true
        leftAxis.axisMinimum = 0
        
        let rightAxis = chartView.rightAxis
        rightAxis.enabled = true
        rightAxis.labelFont = .systemFont(ofSize: 10)
        rightAxis.drawAxisLineEnabled = true
        rightAxis.axisMinimum = 0
        rightAxis.drawGridLinesEnabled = false

        
        chartView.fitBars = true
        
        chartView.animate(yAxisDuration: 2.5)
        
        
        chartView.setExtraOffsets(left: 0, top: -20, right: 0, bottom: 20)
        chartView.chartDescription?.enabled = true
//        chartView.chartDescription?.position = CGPoint.init(x: chartView.width - 20, y: chartView.height - 15)
        chartView.chartDescription?.font = UIFont.systemFont(ofSize: 12)

        chartView.chartDescription?.text = "单位:万元"
        
        chartView.xAxis.labelRotationAngle = 30

        xAxis.valueFormatter = ProfitFormatter()

        chartView.drawMarkers = true
        
        let marker = HorizontalBarMarker(color: UIColor(white: 0, alpha: 0.7), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        
        marker.chartView = chartView
        
        marker.minimumSize = CGSize(width: 80, height: 40)
        
        chartView.marker = marker
        
        let l = chartView.legend
        l.form = .none

        chartView.fitBars = true
//
        updateChartData()
//
//        chartView.animate(yAxisDuration: 1)
        
        self.load(with: "Org")
        // Do any additional setup after loading the view.
    }

    override func updateChartData() {
        
    }
    
    func setDataCount(values: [Double]) {
        
        let barWidth = 6.0
        
        let spaceForBar = 10.0
        
        
        var yVals: Array<BarChartDataEntry> = []
        
        for item in 0 ..< values.count {
            yVals.append(BarChartDataEntry(x: Double(item) * spaceForBar, y: values[item]))
        }
        
        let set1 = BarChartDataSet(values: yVals, label: "")
        set1.drawIconsEnabled = false
        
        set1.colors = [UIColor.hex("0FAFF6")]
        
        let data = BarChartData(dataSet: set1)
        data.setValueFont(UIFont(name:"HelveticaNeue-Light", size:10)!)
        data.barWidth = barWidth
        
        chartView.data = data
        
//        if let max = values.max() {
//            if max < 10 {
//                chartView.leftAxis.axisMaximum = 10
//            }
//        }
//        chartView.xAxis.axisMinimum = 0
//        chartView.xAxis.axisMaximum = 3
//        chartView.xAxis.labelCount = 3
        
    }
    
    override func success(for name: String) -> NetSuccess{
        func getOrgSuc(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    self.companys = data
                    self.popalert()
                }
            }
        }
        
        func orgSuccess(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    self.companys = data
                    if self.companys.count > 0 {
                        let first = self.companys.first!
                        self.selectedCompany = first.contents!["code"]!.rawString()!
                        self.companyField.text = first.contents!["name"]!.rawString()
                    }
                    print(self.companys)
                    self.load(with: "Detail")
                }
            }
        }
        
        func detail(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.contents {
                    
                    print(data)
                    
                    let income = data["income"]?.int ?? 0
                    
                    print(income)
                    
                    let cost = data["cost"]?.int ?? 0
                    
                    print(cost)
                    
                    let profit = income - cost
                    
                    print(profit)
                    
                    let incomeDouble = income / 1000000
                    
                    print(incomeDouble)
                    
                    
                    let costDouble = cost / 1000000
                    print(costDouble)
                    let profitDouble = profit / 1000000
                    print(profitDouble)
                    self.setDataCount(values: [Double(incomeDouble),Double(profitDouble),Double(costDouble)])
                }
            }
        }
        
        switch name {
        case "GetOrg":
            return getOrgSuc
        case "Org":
            return orgSuccess
        default:
            return detail
        }
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        switch name {
        case "Detail":
            return ["orgCode":selectedCompany]
        
        default:
            return [:]
        }
    }
    
    override func path(for name: String) -> String{
        
        return (name == "GetOrg" || name == "Org") ? GETORG : ComprehensiveDetail
        
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
    override var names: Array<String> {
        return ["GetOrg","Detail","Org"]
    }
    
    //响应接口的有效性策略,如果参数不合格，则默认根据String提示
    override func strategy(for name: String) -> (Bool,String?,(()->Void)?){
        return (true,nil,nil)
    }
    
    func popalert() -> Void {
        
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item.contents?["code"]?.rawString() ?? ""
                
                self.load(with: "Detail")
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
